<template>
  <DistributorLayout>
    <div class="products-page">
      <!-- 页面标题和操作区 -->
      <div class="page-header">
        <div class="page-title">
          <h1>产品管理</h1>
          <p class="page-subtitle">管理您的商品信息和设置折扣价格</p>
        </div>

        <!-- <div class="page-actions">
          <button class="btn-create" @click="handleBulkDiscount([])">
            <i class="fas fa-percent"></i>
            批量设置折扣
          </button>
        </div> -->
      </div>

      <!-- 筛选组件 -->
      <!-- <ProductFilter
        :initialFilters="filters"
        @filter-change="handleFilterChange"
      /> -->

      <!-- 商品表格组件 -->
      <div v-if="isLoading" class="loading-container">
        <div class="spinner"></div>
        <span>加载商品数据中...</span>
      </div>

      <ProductsTable v-else :products="filteredProducts" :loading="isLoading"
        :initialSort="{ field: sortField, direction: sortDirection }" @sort-change="handleSortChange"
        @set-discount="handleSetDiscount" @generate-link="handleGenerateLink" @bulk-discount="handleBulkDiscount"
        @bulk-generate-link="handleBulkGenerateLink" @selection-change="handleSelectionChange" />

      <!-- 折扣设置模态框 -->
      <DiscountSettingModal v-if="currentProduct" v-model:visible="discountModalVisible" :product="currentProduct"
        :commission-rate="0.15" :min-discount-percentage="5" @confirm="handleDiscountConfirm"
        @cancel="handleDiscountCancel" />

      <!-- 链接生成成功模态框 -->
      <LinkGeneratedModal v-if="currentProduct && discountData" v-model:visible="linkModalVisible"
        :product="currentProduct" :discount="discountData" @close="handleLinkModalClose" @preview="handlePreviewLink" />
    </div>
  </DistributorLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import DistributorLayout from './DistributorLayout.vue'
import ProductFilter from '@/components/distributor/products/ProductFilter.vue'
import ProductsTable from '@/components/distributor/products/ProductsTable.vue'
import DiscountSettingModal from '@/components/distributor/products/DiscountSettingModal.vue'
import LinkGeneratedModal from '@/components/distributor/products/LinkGeneratedModal.vue'
import { generateProductsData } from '@/utils/mockData'

// 商品数据状态
const products = ref([])
const isLoading = ref(true)
const selectedProducts = ref([])

// 排序状态
const sortField = ref('name')
const sortDirection = ref('asc')

// 模态框状态
const discountModalVisible = ref(false)
const linkModalVisible = ref(false)
const currentProduct = ref(null)
const discountData = ref(null)

// 筛选条件
const filters = ref({
  search: '',
  category: '',
  minPrice: null,
  maxPrice: null,
  restaurant: '',
  status: '',
  hasDiscount: '',
  rating: '',
  sortBy: 'price-asc',
  isHot: false,
  isFavorite: false
})

// 处理筛选条件变化
const handleFilterChange = (newFilters) => {
  filters.value = { ...newFilters }

  // 更新排序状态
  if (newFilters.sortBy) {
    const [field, direction] = newFilters.sortBy.split('-')
    sortField.value = field
    sortDirection.value = direction
  }

  loadProducts()
}

// 处理排序变化
const handleSortChange = (sortInfo) => {
  sortField.value = sortInfo.field
  sortDirection.value = sortInfo.direction

  // 更新筛选条件中的排序
  filters.value.sortBy = `${sortInfo.field}-${sortInfo.direction}`
}

// 处理选择变化
const handleSelectionChange = (selected) => {
  selectedProducts.value = selected
}

// 处理设置折扣
const handleSetDiscount = (product) => {
  currentProduct.value = product
  discountModalVisible.value = true
}

// 处理生成链接
const handleGenerateLink = (product) => {
  // 直接打开折扣设置模态框
  currentProduct.value = product
  discountModalVisible.value = true
}

// 处理批量设置折扣
const handleBulkDiscount = (products) => {
  console.log('批量设置折扣:', products.length ? products.length + '个商品' : '全部商品')
  // 这里实现批量折扣设置逻辑
}

// 处理批量生成链接
const handleBulkGenerateLink = (products) => {
  console.log('批量生成链接:', products.length + '个商品')
  // 这里实现批量链接生成逻辑
}

// 处理折扣模态框确认
const handleDiscountConfirm = (data) => {
  console.log('折扣设置已确认:', data)
  // 保存折扣数据
  discountData.value = data

  // 显示链接生成成功模态框
  discountModalVisible.value = false
  setTimeout(() => {
    linkModalVisible.value = true
  }, 300)
}

// 处理折扣模态框取消
const handleDiscountCancel = () => {
  console.log('折扣设置已取消')
}

// 处理链接模态框关闭
const handleLinkModalClose = () => {
  linkModalVisible.value = false
  // 清除折扣数据
  discountData.value = null
}

// 处理预览链接
const handlePreviewLink = (link) => {
  console.log('预览链接:', link)
  // 可以在这里添加其他预览逻辑
}

// 过滤并排序后的商品数据
const filteredProducts = computed(() => {
  let filtered = [...products.value]

  // 应用筛选逻辑
  if (filters.value.search) {
    const searchTerm = filters.value.search.toLowerCase()
    filtered = filtered.filter(p =>
      p.name.toLowerCase().includes(searchTerm) ||
      p.description.toLowerCase().includes(searchTerm)
    )
  }

  if (filters.value.category) {
    filtered = filtered.filter(p => p.category === filters.value.category)
  }

  if (filters.value.minPrice !== null) {
    filtered = filtered.filter(p => p.price >= filters.value.minPrice)
  }

  if (filters.value.maxPrice !== null) {
    filtered = filtered.filter(p => p.price <= filters.value.maxPrice)
  }

  if (filters.value.restaurant) {
    filtered = filtered.filter(p => p.restaurant.name === filters.value.restaurant)
  }

  if (filters.value.status) {
    filtered = filtered.filter(p => p.status === filters.value.status)
  }

  if (filters.value.hasDiscount === 'yes') {
    filtered = filtered.filter(p => p.currentDiscount !== null)
  } else if (filters.value.hasDiscount === 'no') {
    filtered = filtered.filter(p => p.currentDiscount === null)
  }

  if (filters.value.rating) {
    const minRating = parseFloat(filters.value.rating)
    filtered = filtered.filter(p => p.rating >= minRating)
  }

  if (filters.value.isHot) {
    filtered = filtered.filter(p => p.isHot)
  }

  if (filters.value.isFavorite) {
    filtered = filtered.filter(p => p.isCustomerFavorite)
  }

  // 排序
  filtered.sort((a, b) => {
    let aValue, bValue

    switch (sortField.value) {
      case 'name':
        aValue = a.name
        bValue = b.name
        return sortDirection.value === 'asc'
          ? aValue.localeCompare(bValue)
          : bValue.localeCompare(aValue)
      case 'price':
        aValue = a.price
        bValue = b.price
        break
      case 'discount':
        aValue = a.currentDiscount || a.price
        bValue = b.currentDiscount || b.price
        break
      case 'commission':
        aValue = a.totalCommission || 0
        bValue = b.totalCommission || 0
        break
      default:
        aValue = a.name
        bValue = b.name
        return sortDirection.value === 'asc'
          ? aValue.localeCompare(bValue)
          : bValue.localeCompare(aValue)
    }

    return sortDirection.value === 'asc'
      ? aValue - bValue
      : bValue - aValue
  })

  return filtered
})

// 加载商品数据
const loadProducts = async () => {
  isLoading.value = true

  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))

    // 获取模拟数据
    products.value = generateProductsData(30)
  } catch (error) {
    console.error('加载商品数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 初始加载数据
onMounted(() => {
  loadProducts()
})
</script>

<style lang="scss" scoped>
.products-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;

    .page-title {
      h1 {
        font-size: 24px;
        font-weight: 700;
        color: #2F3542;
        margin: 0 0 8px 0;
      }

      .page-subtitle {
        font-size: 14px;
        color: #6C757D;
        margin: 0;
      }
    }

    .page-actions {
      .btn-create {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background-color: #FF4757;
        color: white;
        border: none;
        border-radius: 6px;
        padding: 10px 16px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;

        i {
          margin-right: 8px;
        }

        &:hover {
          background-color: darken(#FF4757, 8%);
          transform: translateY(-2px);
          box-shadow: 0 4px 8px rgba(255, 71, 87, 0.3);
        }
      }
    }
  }

  .loading-container {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    padding: 32px;
    min-height: 300px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .spinner {
      width: 40px;
      height: 40px;
      border: 4px solid #f3f3f3;
      border-top: 4px solid #FF4757;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 16px;
    }

    span {
      color: #666;
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .products-page {
    .page-header {
      flex-direction: column;

      .page-actions {
        margin-top: 16px;
      }
    }
  }
}
</style>
